/**
 * Created by apple on 16/3/31.
 */
class Controller {
    constructor (systemService, uiNotification, statusMap, orgId, CodeText, $modalInstance, $timeout) {
        "ngInject"
        this.uiModal     = $modalInstance;
        this.service     = systemService;
        this.notify      = uiNotification;
        this.status      = statusMap;
        this.codeText    = CodeText;
        this.timeout     = $timeout;
        this.data = {
            parentOrgId    : orgId,
            statusCd       : "S0A",
            orgCode        : "",
            orgName        : "",
            commonRegionId : "",
            sysPostId      : 1
        }
    }
    save() {

        if (this.submitting) return;
        this.submitting = true;

        this.service.insert('org',this.data).then( (res) => {

            angular.extend(this.data, {
                id: res.data,
                orgId: res.data,
                createDate: +(new Date)
            })
            
            this.uiModal.close(this.data);

            this.notify.success({
                'title'  : '提示',
                'message': '操作成功!'
            });
            
        }).catch( (data) => {
            if (data.resultCode == 1062) {
                this.notify.error({
                    'title'  : '提示',
                    'message': this.codeText.org
                });
            }
        }).finally( () => {
            // 隐藏 loading
            this.submitting = false;
        });
    }
    checkValid (field) {
        if ( field.$pristine ) {
            field.$pristine = false;
        }
    }

    checkSame () {
        if (this.data.orgName) {
            if (this.checking) return;
            this.checking = true;
            this.timeout(() => {
                this.service.checkExist('org',{
                    orgName: this.data.orgName,
                    parentOrgId: this.data.parentOrgId
                }).then((res) => {
                    this.checking = false;
                    this.isSame = res.data;
                    if (res.data) {
                        this.notify.error({
                            'title'  : '提示',
                            'message': '存在同名组织, 不可重复添加!'
                        });
                    }
                })
            }, 250)
        }
    }

    cancel() {
        this.uiModal.dismiss('cancel')
    }
}

export default Controller;